from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError


# 审批流类
class Workflow(models.Model):
    _inherit = 'sb.workflow'

    # 关联销售单据
    sale_order_id = fields.Many2one('sale.order', string="Related Documents", ondelete="cascade")

    workflow_type = fields.Selection(selection_add=[
        ('sale', 'Sale')
    ], ondelete={'activity': 'cascade'})
    commitment_date = fields.Datetime(string="Delivery Date", related='sale_order_id.commitment_date')
    product_template_id = fields.Many2one('product.template', string='Product', related="sale_order_id.product_id")
    attachment_ids = fields.One2many('ir.attachment', 'res_id', compute='_compute_checkout_attachments',
                                     string='Sale Order Attachment', readonly=True, store=True)
    sale_qty = fields.Integer(string="QTY", related='sale_order_id.qty')

    # 以下字段仅限销售单审批使用
    opportunity_id = fields.Many2one('crm.lead', string="Opportunity", related='sale_order_id.opportunity_id')
    sale_name = fields.Char(string="Sale Name", related='sale_order_id.name')
    sale_po = fields.Char(string="PO", related='sale_order_id.po')
    sale_validity_date = fields.Date(string="Validity Date", related='sale_order_id.validity_date')
    sale_date_order = fields.Datetime(string="Date Order", related='sale_order_id.date_order')
    sale_commitment_date = fields.Datetime(string="Commitment Date", related='sale_order_id.commitment_date')
    sale_incoterm = fields.Many2one('account.incoterms', string="Incoterm", related='sale_order_id.incoterm')
    sale_order_type = fields.Selection(string="Order Type", related='sale_order_id.order_type')
    sale_special_order_type = fields.Selection(string="Special Order Type", related='sale_order_id.special_order_type')
    sale_partner_id = fields.Many2one('res.partner', string="Customer", related='sale_order_id.partner_id')
    sale_note = fields.Html(string="Remark", related='sale_order_id.note')

    # 销售订单行
    sale_qta = fields.Boolean(string="QTA", compute='_compute_line')
    sale_product_status = fields.Selection([('S', 'NPI'),
                                            ('P', 'MP'),
                                            ('T', 'Test'),
                                            ('Q', 'QTA+NPI'), ], string="Product Status", compute='_compute_line')
    sale_pn = fields.Char(string="PN", compute='_compute_line')
    sale_pn_rev = fields.Char(string="PN REV", compute='_compute_line')
    sale_product_uom = fields.Many2one('uom.uom', string="UOM", compute='_compute_line')

    # 报价单信息
    crm_layer = fields.Integer(string="Layer", related='opportunity_id.layer')
    crm_unit_size_width = fields.Float(string="Unit Size(W/mm)", related='opportunity_id.unit_size_width')
    crm_unit_size_long = fields.Float(string="Unit Size(L/mm)", related='opportunity_id.unit_size_long')
    crm_board_thk = fields.Float(string="Board Thk.(mm)", related='opportunity_id.board_thk')
    crm_panel_size_width = fields.Float(string="Panel Size(W/mm)", related='opportunity_id.panel_size_width')
    crm_panel_size_long = fields.Float(string="Panel Size(L/mm)", related='opportunity_id.panel_size_long')
    crm_surface_finish = fields.Char(string="Surface Finish", related='opportunity_id.surface_finish')
    crm_pcs_in_panel = fields.Integer(string="Pcs/Panel", related='opportunity_id.pcs_in_panel')
    crm_board_material = fields.Char(string="Board Material", related='opportunity_id.board_material')
    crm_internal_copper_thk = fields.Integer(string="Int Copper Thk(um)", related='opportunity_id.internal_copper_thk')
    crm_external_copper_thk = fields.Integer(string="Ext Copper Thk(um)", related='opportunity_id.external_copper_thk')
    crm_utilization_rate = fields.Float(string="Utilization Rate", related='opportunity_id.utilization_rate')

    @api.depends('sale_order_id')
    def _compute_checkout_attachments(self):
        for sb_fo in self:
            sale_id = sb_fo.sale_order_id
            if not sale_id:
                continue
            # 获取销售订单的附件
            attachment = sale_id._get_mail_thread_data(['attachments'])
            attachments = attachment.get('attachments', [])
            if not isinstance(attachments, list):
                continue
            attachment_ids = []
            for attach in attachments:
                if not attach.get('id'):
                    continue
                # 不可重复使用原来的,需要copy一条
                attach = self.env['ir.attachment'].browse(attach.get('id')).copy()
                if not attach:
                    continue
                attach.write({
                    'res_model': 'sb.workflow',
                })
                attachment_ids.append(attach.id)
            if attachment_ids:
                sb_fo.write({
                    'attachment_ids': [(6, 0, attachment_ids)]
                })

    @api.constrains('sale_order_id')
    def constraint_sale_order_id(self):
        remark_list = []
        for line in self.sale_order_id.order_line.filtered(lambda x: x.product_type != 'service'):
            remark_list.append(line.product_id.name)
        self.remark = '\n'.join(remark_list)

    @api.depends('sale_order_id')
    def _compute_line(self):
        for record in self:
            line = record.sale_order_id.order_line.filtered(lambda x: x.product_type == 'product')
            if len(line) > 1:
                line = line[0]
            record.sale_qta = line.s_qt
            record.sale_product_status = line.s_materiel_status
            record.sale_pn = line.pn
            record.sale_pn_rev = line.pn_rev
            record.sale_product_uom = line.product_uom.id


# 审批流类
class WorkflowItem(models.Model):
    _inherit = 'sb.workflow.item'

    # 审批流产品
    sb_workflow_pro = fields.Many2one('product.template', related="sb_workflow_id.product_template_id")
    is_jmi_upload = fields.Boolean(string="JMI Upload Sale")
    is_engineering = fields.Boolean(string="Is Engineering")
    sale_po = fields.Char(string="PO", related='sb_workflow_id.sale_po')
    sale_order_id = fields.Many2one('sale.order', string="MO", related='sb_workflow_id.sale_order_id')

    def review(self):
        qty_available = 0
        free_qty = 0
        incoming_qty = 0
        rec = super(WorkflowItem, self).review()
        if rec['context'].get('workflow_type', '') == 'sale' and rec['context'].get('is_plan', False):
            qty_available = self.sb_workflow_id.product_template_id.product_variant_id.qty_available
            free_qty = self.sb_workflow_id.product_template_id.product_variant_id.free_qty
            incoming_qty = self.sb_workflow_id.product_template_id.product_variant_id.incoming_qty
            planned_receiving_date = self.sb_workflow_id.sale_order_id.planned_receiving_date
            rec['context'].update(planned_receiving_date=planned_receiving_date)
        rec['context'].update({
            'qty_available': qty_available,
            'free_qty': free_qty,
            'incoming_qty': incoming_qty,
            'product_template_id': self.sb_workflow_id.product_template_id.id
        })
        return rec
